package com.buba.springcloud.controller;
import com.buba.springcloud.entities.CommonResult;
import com.buba.springcloud.entities.HfUser;
import com.buba.springcloud.pojo.CheckUser;
import com.buba.springcloud.service.LoginService;
import com.buba.springcloud.util.JwtUtil;
import com.buba.springcloud.util.RedisUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * autor：肖宝兴
 **/
@RestController
@Slf4j
@RequestMapping("/frontdesk")
public class LoginController {
    @Resource
    private LoginService loginService;

    @Resource
    private RedisUtil redisUtil;

    //登录
    @PostMapping("/login")
    public CommonResult login(@RequestBody HfUser hfUser) {
        HfUser user = loginService.login(hfUser.getUsername());
        String jwt = "";
        if (user != null) {
            if (user.getPassword().equals(hfUser.getPassword())) {
                jwt = JwtUtil.createJWT(1000 * 60 * 30 , user);
                //把查出来的数据存放进redis
                redisUtil.set("fuser"+String.valueOf(user.getId()), user,60);
                return new CommonResult<>(200, "登录成功", jwt);
            }
        }
        return new CommonResult<>(500, "登陆失败");
    }

    //注销
    @GetMapping("/signOut")
    public CommonResult signOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            new CommonResult<>(200, "注销成功");
        }
        String id = claims.get("id").toString();
        redisUtil.del(id);
        return new CommonResult<>(200, "注销成功");
    }

    //使用手机验证登录
    //模拟产生验证码 60s
    @GetMapping("/createCode/{phone}")
    public CommonResult createCode(@PathVariable("phone") String phone) {
        HfUser userInfo = loginService.login(phone);
        if (userInfo != null) {
            String str = "0,1,2,3,4,5,6,7,8,9";
            String str2[] = str.split(",");//将字符串以,分割
            Random rand = new Random();//创建Random类的对象rand
            int index = 0;
            String verificationCode = "";//创建内容为空字符串对象randStr
            for (int i = 0; i < 6; ++i) {
                index = rand.nextInt(str2.length - 1);//在0到str2.length-1生成一个伪随机数赋值给index
                verificationCode += str2[index];//将对应索引的数组与randStr的变量值相连接
            }
            //放入redis 时效（s）60
            redisUtil.set(phone, verificationCode, 60);
            return new CommonResult(200, "验证码创建成功", verificationCode);
        }
        return new CommonResult(500, "创建失败，手机号未注册");
    }

    //验证码校验
    @PostMapping("/check")
    public CommonResult check(@RequestBody CheckUser checkUser) {
        String verificationCode = null;
        String jwt = null;
        //这个就是实例
        try {
            verificationCode = redisUtil.get(checkUser.getPhone()).toString();
        } catch (Exception e) {
            return new CommonResult(500, "验证码已过期");
        }
        if (checkUser.getCode().equals(verificationCode)) {
            HfUser userInfo = loginService.login(checkUser.getPhone());
            jwt = JwtUtil.createJWT(1000 * 60 * 30, userInfo);
            //把查出来的数据存放进redis
            redisUtil.set(String.valueOf(userInfo.getId()), userInfo, 60*30);
            return new CommonResult(200, "验证成功", jwt);
        } else {
            return new CommonResult(500, "验证失败");
        }
    }
}
